package com.zc.study.java开发实战1200例.第十章_网络应用基础.网络地址解析_10_1.多线程下载资源;

import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sound.midi.Soundbank;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLOutput;

public class DownLoad {
    private final static Logger logger= LoggerFactory.getLogger(DownLoad.class);

    public static void download(String url, String dest, int threadNum) throws Exception {
        logger.debug("开始下载");
        URL downUrl = new URL(url);//创建网络资源的url
        HttpURLConnection conn = (HttpURLConnection) downUrl.openConnection();//打开网络连接
        long fileLength = -1;//用于储存文件长度的变量
        int stateFlagCode = conn.getResponseCode();//获取连接状态标记代码
        if (stateFlagCode == 200) {//判断网络是否连接正常
            fileLength = conn.getContentLength();//获取文件的长度
            conn.disconnect();//取消网络连接
        }
        if (fileLength > 0) {
            long byteCounts = fileLength / threadNum + 1;//计算每个线程的字节数
            File file = new File(dest);//创建目标文件的file对象
            int i = 0;
            while(i<threadNum){
                long startPosition = byteCounts*i;//定义开始位置
                long endPosition = byteCounts*(i+1);//定义结束位置
                if(i==threadNum-1){
                    logger.debug("线程"+i+"启动");
                    DownMultiThread fileThread = new DownMultiThread(url,file,startPosition,fileLength);//创建DownMultiThread线程的实例
                    new Thread(fileThread).start();//启动线程对象
                }else {
                    DownMultiThread fileThread = new DownMultiThread(url,file,startPosition,endPosition);
                    new Thread(fileThread).start();
                }
                i++;
            }
            System.out.println("完成网络资源的下载");
        }


    }
}
